import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcrypt';
import { JwtBlacklistService } from '@/api/auth/jwt-blacklist.service';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UserService,
    private jwtService: JwtService,
    @Inject(JwtBlacklistService)
    private readonly jwtBlacklistService: JwtBlacklistService,
  ) {}

  async checkPassword(plainPassword, hashedPassword) {
    const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
    return isMatch;
  }

  async login(loginAuthDto): Promise<{ access_token: string }> {
    const user = await this.usersService.findOne(loginAuthDto.name);
    const payload = { sub: user.id, name: user.name };
    return await this.checkPassword(loginAuthDto.password, user.password)
      .then(async (isMatch) => {
        if (!isMatch) {
          throw new UnauthorizedException('Invalid credentials');
        }
        return {
          access_token: await this.jwtService.signAsync(payload),
        };
      })
      .catch((err) => {
        console.error(err);
        throw err;
      });
  }

  async logout(token: string) {
    this.jwtBlacklistService.addToBlacklist(token);
  }
}
